package com.yyt.module_main.act;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yyt.libsrc.conf.Consts;
import com.yyt.libsrc.helper.MsgHelper;
import com.yyt.libsrc.router.RouteTable;
import com.yyt.libsrc.router.RouterHelper;
import com.yyt.module_main.R;
import com.yyt.module_main.databinding.ActivityPayBinding;
import com.yyt.module_main.vm.PayVM;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import top.lixb.libcommon.base.RefreshableActivity;
import top.lixb.libcommon.log.L;

@Route(path = RouteTable.main_pay)
public class PayActivity extends RefreshableActivity<ActivityPayBinding> {


    private PayVM mVm;
    private WebView mWebView;

    @Override
    protected void init() {
        mVm = new PayVM();
        mRefreshContentBinding.setVm(mVm);
        setTitle("支付");
        mRefreshContentBinding.groupWechat.setClickable(false);
        mRefreshContentBinding.groupWechat.setEnabled(false);
        mRefreshContentBinding.groupWechat.setAlpha(0.5f);
        mRefreshContentBinding.rbWechat.setChecked(false);
        mRefreshContentBinding.rbtnAlipay.setChecked(true);
        initWebView();
        if (null != getIntent() && null != getIntent().getExtras()) {
            mVm.payamount.set(getIntent().getStringExtra("amount"));
            mVm.payurl.set(getIntent().getStringExtra("url"));
            mVm.afterRate.set(getIntent().getStringExtra("afterRate")+"%");
        }

        mRefreshContentBinding.groupAlipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshContentBinding.rbWechat.setChecked(false);
                mRefreshContentBinding.rbtnAlipay.setChecked(true);
            }
        });

        mRefreshContentBinding.groupWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshContentBinding.rbWechat.setChecked(true);
                mRefreshContentBinding.rbtnAlipay.setChecked(false);
            }
        });

        mRefreshContentBinding.btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mRefreshContentBinding.rbtnAlipay.isChecked()) {
                    String data = mVm.payurl.get();
                    if (!TextUtils.isEmpty(data)) {
                        mRefreshContentBinding.web.loadDataWithBaseURL(null, data,"text/html","utf-8",null);
                    }
                } else if (mRefreshContentBinding.rbWechat.isChecked()) {
                    MsgHelper.showToast("暂不支持微信支付,请选择支付宝支付");
                }
            }
        });
    }

    private void initWebView() {
        mWebView = mRefreshContentBinding.web;
        WebSettings settings = mWebView.getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
        settings.setTextSize(WebSettings.TextSize.NORMAL);
        //其他细节操作
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        settings.setAllowFileAccess(false); //设置可以访问文件
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式

        // 特别注意：5.1以上默认禁止了https和http混用，以下方式是开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setVerticalScrollbarOverlay(true);
        mWebView.setWebViewClient(new MyWebViewClient());
    }

    @Override
    protected int initRefreshLayout() {
        return R.layout.activity_pay;
    }

    @Override
    protected void getData(boolean refresh) {

    }

    @Override
    public void onBackPressed() {
        if (null != mWebView && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now


        if (mWebView != null) {
            mWebView.setWebChromeClient(null);
            mWebView.setWebViewClient(null);
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearCache(true);
            mWebView.removeAllViews();
            try {
                mWebView.destroy();
            } catch (Throwable t) {
                t.printStackTrace();
            }
            mWebView = null;
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            L.e("shoulO loadurl:" + url);


            if (url.startsWith("weixin://wap/pay?")) { //微信支付
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            } else {


                /**
                 * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次 (拦截支付宝支付)
                 */
                final PayTask task = new PayTask(PayActivity.this);
                boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                    @Override
                    public void onPayResult(final H5PayResultModel result) {
                        final String url = result.getReturnUrl();
                        String resultCode = result.getResultCode();
                        String resultMsg = "";
                        switch (Integer.valueOf(resultCode)) {
                            case 9000:
                                resultMsg = "订单支付成功";
                                break;
                            case 8000:
                                resultMsg = "正在处理中";
                                break;
                            case 4000:
                                resultMsg = "订单支付失败";
                                break;
                            case 5000:
                                resultMsg = "重复请求";
                                break;
                            case 6001:
                                resultMsg = "用户中途取消";
                                break;
                            case 6002:
                                resultMsg = "网络连接出错";
                                break;
                        }
                        Flowable.just(resultMsg).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                MsgHelper.showToast(s);
                            }
                        });


                        if (!TextUtils.isEmpty(url)) {
                            PayActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    view.loadUrl(url);
                                }
                            });
                        }

                        if (Integer.valueOf(resultCode) == 9000) {
                            finish();
                        }
                    }
                });

                L.e("url 拦截成功:" + isIntercepted);
                /**
                 * 判断是否成功拦截
                 * 若成功拦截，则无需继续加载该URL；否则继续加载
                 */
                if (!isIntercepted) {
//                    view.loadUrl(url);
                    Map<String, String> extraHeaders = new HashMap<String, String>();
                    extraHeaders.put("Referer", Consts.Config.testMode ? "http://pay.veejava.com/" : "http://admin.huiyie.com/");
                    view.loadUrl(url, extraHeaders);
                    MsgHelper.showToast("load url" + url);
                }
            }

            return true;
        }
    }

}
